package com.lifeng.controller;

import com.lifeng.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by lifeng on 2018/4/13.
 */
@RestController
public class UserConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping("/user/consumer/{id}")
    public Object getUser(@PathVariable String id){
        //String url = "http://localhost:8080/user/"+id;
        //此时不用在硬编码了,通过服务名称调用
        String url = "http://user-service-provider/user/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    /***/
    @RequestMapping("/user/consumer2/{id}")
    public Object getUser2(@PathVariable String id){
        ServiceInstance serviceInstance = loadBalancerClient.choose("user-service-provider");//选择一个服务名
        System.out.println("===" + ":" + serviceInstance.getServiceId() + ":" + serviceInstance.getHost() + ":"
                + serviceInstance.getPort());// 打印当前调用服务的信息
        String url = "http://user-service-provider/user/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }
}
